package com.etlmaster.util.vfs;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.ftp.FtpFileSystemConfigBuilder;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;

/**
 * @author Larry
 * @copyright Larry@etlMaster
 * @since 2017-09-10
 */
public class VfsUtils {
	
	private FileSystemManager fsManager;
	
	private FileSystemOptions opts = new FileSystemOptions();
	
	private static VfsUtils instance = new VfsUtils();
	
	private VfsUtils(){
		try {
			fsManager = VFS.getManager();
			SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
			FtpFileSystemConfigBuilder.getInstance().setPassiveMode(opts, true);
			StandardFileSystemManager mgr = (StandardFileSystemManager) fsManager;
			synchronized (mgr) {
				if (!ArrayUtils.contains(mgr.getSchemes(), "hdfs")) {
					mgr.addProvider("hdfs", new HdfsFileProvider());
				}
			}
		} catch (FileSystemException e) {
			e.printStackTrace();
		}
	}
	
	public static VfsUtils getInstance(){
		return instance;
	}
	
	public FileSystemManager getFileSystemManager(){
		return fsManager;
	}
	
	/**
	 * 需要手工关闭FileObject
	 * @param absFilePath
	 * @return
	 */
	public FileObject resolveFile(String absFilePath) {
		FileObject fileObject = null;
		try {
			fileObject = fsManager.resolveFile(absFilePath, opts);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return fileObject;
	}
	
	public void closeFileObject(FileObject fileObject){
		if(fileObject!=null){
			try {
				fileObject.close();
			} catch (FileSystemException e) {
				e.printStackTrace();
			}
		}
	}
}
